package leetcode.newVersion.Hash;

import java.util.Arrays;
import java.util.HashMap;

public class lc1 {
    /*
    用hash的方式解题
     */
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] res = new int[2];

        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (!map.containsKey(diff)) {//没找到成功配对的数字，就将当前数字放入hashmap中
                map.put(nums[i], i);//key是数值，value是对应的索引
            }else {//匹配成功，返回当前索引和查询到数字的索引
                res[0] = i;
                res[1] = map.get(diff);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        lc1 l = new lc1();
        int[] nums1 = new int[]{2, 7, 11, 15};
        System.out.println(Arrays.toString(l.twoSum(nums1, 9)));

        int[] nums2 = new int[]{3,2,4};
        System.out.println(Arrays.toString(l.twoSum(nums2, 6)));

        int[] nums3 = new int[]{3, 3};
        System.out.println(Arrays.toString(l.twoSum(nums3, 6)));
    }
}
